# -*- coding: utf-8 -*-

$:.unshift 'lib'

require 'dcmgr/rubygems'

require 'rake/clean'
CLOBBER.include("vendor/bundle/**/*", "*.gem")

task :environment do
  require 'dcmgr'

  Dcmgr::Configurations.load Dcmgr::Configurations::Dcmgr, [
    ENV['CONF_PATH'].to_s,
    '/etc/wakame-vdc/dcmgr.conf',
    File.expand_path('config/dcmgr.conf', Dcmgr::DCMGR_ROOT)
  ]
end

task :test_environment do
  require 'dcmgr'

  Dcmgr::Configurations.load(Dcmgr::Configurations::Dcmgr,
    [File.expand_path('spec/minimal_dcmgr.conf', Dcmgr::DCMGR_ROOT)])
end

def database_up
  Dcmgr.run_initializers('logger', 'sequel')

  Sequel.extension :migration
  Sequel::Migrator.apply(Sequel::DATABASES.first,
                         File.expand_path('config/db/migrations', Dcmgr::DCMGR_ROOT),
                         9999)
end

def database_down
  Dcmgr.run_initializers('logger', 'sequel')

  Sequel.extension :migration
  Sequel::Migrator.apply(Sequel::DATABASES.first,
                         File.expand_path('config/db/migrations', Dcmgr::DCMGR_ROOT),
                         0)
end

namespace :db do
  desc 'Up all database migrations'
  task :up => [ :environment ] do
    database_up
  end

  desc 'Down all database migrations'
  task :down => [ :environment ] do
    database_down
  end

  task :init => [:up] do
    STDERR.puts "WARN: deprecated task. Please use db:up."
  end

  task :drop => [:down] do
    STDERR.puts "WARN: deprecated task. Please use db:down."
  end
end

namespace :test do
  namespace :db do
    task :up => [ :test_environment ] do
      database_up
    end

    desc 'Down all database migrations'
    task :down => [ :test_environment ] do
      database_down
    end
  end
end

desc 'run bundle command to install vendored gems.'
task :bundle do
  sh <<_ENDCMD
mkdir .bundle
cat <<END_ > .bundle/config
---
BUNDLE_DISABLE_SHARED_GEMS: "1"
BUNDLE_PATH: vendor/bundle
END_
_ENDCMD
  sh "bundle install"
end
